#-*- coding:utf-8 -*-
#DESCRIPTION This script used for getting files via FTP and sending it as a attachment.
#AUTHOR baoxiwu<baoxiwu@boe.com.cn>, C&M, CIM, BOEDT
#DATE 2011-07-18
#VERSION see __VERSION__
#NOTICE&WARNINGS KEEP YOUR OWN ACCOUNT SAFE.



#
#program version
#
__VERSION__ = "v0.9.0"


#CONST VARIABLES DEFINITION
#FTP ACCOUNT INFO
__CONST_FTP_HOST__ = '10.90.247.1'
__CONST_FTP_USER__ = 'bao'
__CONST_FTP_PASSWD__ = '890711'


#log folder
__CONST_LOG_PATH__ = './log'
#log file to record TRANSACTION log.
__CONST_LOG_TRANSACTION_PATH_PREFIX__ = './log/pipe_transaction.'
#log file to record exceptions thrown by functions
__CONST_LOG_EXCEPTION_PATH_PREFIX__ = './log/pipe_exception.'
#consts for function log() to determine the type of log to record.
__CONST_LOG_TYPE_TRANSACTION__ = 0  #LOG TYPE : TRANSACTION LOG
__CONST_LOG_TYPE_EXCEPTION__ = 1    #LOG TYPE : EXCEPTION LOG


#
#CALENDAR TYPE DEFINITION
#
__CONST_CAL_TYPE_DATE__ = 0
__CONST_CAL_TYPE_TIME__ = 1
__CONST_CAL_TYPE_DATE_AND_TIME__ = 2


#
#const variables for sending emails.
#WARNINGS:All these account informations are protected by local or
#international law.
#
__CONST_MAILTO_LIST__ = ["baoxiwu@boe.com.cn", "jiangyong@boe.com.cn"]#["baoxiwu@boe.com.cn","jiangyong@boe.com.cn"]
__CONST_MAIL_ADDRESS__ = "BOE-DT-SA@bao1xia.info"
__CONST_MAIL_HOST__ = "smtp.gmail.com"
__CONST_MAIL_USERNAME__ = "BOE-DT-SA@bao1xia.info"
__CONST_MAIL_PASSWD__ = "nimawoshi2b"
__CONST_MAIL_SUBJECT__ = "SYSTEM INFO"
__CONST_MAIL_CONTENT__ = "Dear all,\ntoday's report SEE attachment.\n"




#
#@description initialize the programme.
#
def init():
    import os
    print "Initializing..."
    
    #if file does not exist.
    if not os.path.exists(__CONST_LOG_PATH__):
        os.makedirs(__CONST_LOG_PATH__)

    print "Initialized..."
    return True




#
#@description get file(s) which match the para $patter
#
#@para
#       $host
#       $user
#       $passwd
#       $pattern
#
#@return
#       $path of file matched or None
#
def ftp_browser(host, user, passwd, pattern, path, localpath):
    from ftplib import FTP
    import re

    p = re.compile(pattern)
    ftp = FTP(host)
    
    try:
        print "FTP Login..."
        ftp.login(user, passwd)
        ftp.getwelcome()

        print "FTP CWD..."
        ftp.cwd(path)
    
        lst = ftp.nlst()
        fname = None
        for name in lst:
            #loop for getting the latest file.
            if not (p.match(name) is None):
                fname = name
                #print "___" + fname

        #print "out___" + fname
        if not (fname is None):
            local_path = localpath + fname
            
            f = open(local_path, 'wb')
            
            filename = 'RETR ' + fname

            print "FTP Downloading file..."
            ftp.retrbinary(filename, f.write)

            print "FTP Deleting file..."
            ftp.delete(fname)
            ftp.quit()
            return fname;
    except Exception,e:
        log(getDateTime(__CONST_CAL_TYPE_DATE_AND_TIME__), str(e), __CONST_LOG_TYPE_EXCEPTION__)
        return None

    
#
#@description send emails to specific members.
#
#@para
#       $to_list = send to
#       $sub = subject
#
#       $content = email content
#
#@return
#       $True if sending emails succeed.
#
def send_mail(to_list, sub, content, filename):
    from smtplib import SMTP
    from email.mime.text import MIMEText
    from email.Header import Header
    from email.MIMEMultipart import MIMEMultipart


    print "Sending mail..."
    server = SMTP(__CONST_MAIL_HOST__)
    server.set_debuglevel(0) # or 1 for verbosity
    server.ehlo(__CONST_MAIL_ADDRESS__)
    server.starttls()
    server.ehlo(__CONST_MAIL_ADDRESS__)  # say hello again
    server.login(__CONST_MAIL_USERNAME__, __CONST_MAIL_PASSWD__)
    
    msg = MIMEMultipart()
    #mail text content setting.
    text_msg = MIMEText(content)
    msg.attach(text_msg)

    #attachment setting.
    att = MIMEText(open(filename).read(), 'base64', 'utf-8')
    att['Content-Type'] = "text/plain"
    att['Content-Disposition'] = 'attachment;filename=\"'+filename[filename.find("sys"):]+'\"'

    sender = '<' + __CONST_MAIL_USERNAME__ + '>'
    msg['Subject'] = sub
    msg['From'] = sender
    msg['To'] = ";".join(to_list)
    msg.attach(att)
    
    try:
        server.sendmail(sender,to_list,msg.as_string())
        server.quit()
        print "Mail sent..."
        
        return True
    except Exception,e:
        log(getDateTime(__CONST_CAL_TYPE_DATE_AND_TIME__), str(e), __CONST_LOG_TYPE_EXCEPTION__)
        return None



#
#@description get system date and time
#
#@para
#
#@return
#       $dateTime
#
def getDateTime(typ):
    import time

    if typ == __CONST_CAL_TYPE_DATE_AND_TIME__:
        dateTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    elif typ == __CONST_CAL_TYPE_DATE__:
        dateTime = time.strftime("%Y-%m-%d",time.localtime())
    else:
        dateTime = time.strftime("%H:%M:%S",time.localtime())
        
    return dateTime



#
#@description record tracnsactions of system. Add date,time and content into log file.
#
#@para
#       $date_time = system date and time
#       $content = log content
#       $typ = log type:error log | exception log
#@return
#       $True write into log files successfully.
#
def log(date_time,content,typ):
    #log file name.
    global FILENAME
    #please make sure that you have the PERMISSION\ 
    #to write the log files if you r using unix[-like] system:__CONST_LOG_FILE__ and __CONST_EXCEPTION_LOG__

    #system log
    if(typ == __CONST_LOG_TYPE_TRANSACTION__):
        FILENAME = __CONST_LOG_TRANSACTION_PATH_PREFIX__ + getDateTime(__CONST_CAL_TYPE_DATE__) + ".log"
        logFile = open(FILENAME, 'a')
    #exception log
    else:
        FILENAME = __CONST_LOG_EXCEPTION_PATH_PREFIX__ + getDateTime(__CONST_CAL_TYPE_DATE__) + ".log"
        logFile = open(FILENAME, 'a')

    print "Writing log..."
    logFile.write('[SysInfoCrawler ' + __VERSION__ + ' log] [' + date_time + ']  ' + content + '\n')
    logFile.close();
    print "Log wrote..."
    return True



#
#main part
#    
if __name__ == "__main__":
    import os

    init()
    filename = ftp_browser(__CONST_FTP_HOST__, __CONST_FTP_USER__, __CONST_FTP_PASSWD__, "sysinfocrawler-\d{6}-\d{4}.log", "/home/bao", "./")
    
    if not (filename is None):
        send_mail(__CONST_MAILTO_LIST__, __CONST_MAIL_SUBJECT__ + " " + getDateTime(__CONST_CAL_TYPE_DATE__), __CONST_MAIL_CONTENT__, filename)

        log(getDateTime(__CONST_CAL_TYPE_DATE_AND_TIME__), "FILE " + filename + " SENT.", __CONST_LOG_TYPE_TRANSACTION__)
        
        print "Deleting local file..."
        os.remove(filename)

    print "No file found..."
    log(getDateTime(__CONST_CAL_TYPE_DATE_AND_TIME__), "NOTHING FOUND!", __CONST_LOG_TYPE_TRANSACTION__)
